import { useModel } from "umi";
import { useReactive } from "ahooks";

import { AllApplications, FindApplicationTypes, FindApplicationTypeVersions } from "../../_graphql/organization/application";

const useApplication = () => {
    const { graphqlFetchPlatform } = useModel("global");

    const state = useReactive({
        dataLoading: false,
        submitLoading: false,
        applications: [],
        totalCount: 0,
        clients: [],
        versions: [],
    });

    const loadApplications = async ({ pageSize, page, appName, acName, aoName, appRole, appSduu }) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: AllApplications,
            variables: {
                first: pageSize,
                offset: (page - 1) * pageSize || 0,
                appName: appName || undefined,
                acName: acName || undefined,
                aoName: aoName || undefined,
                appRole: appRole || undefined,
                appSduu: appSduu || undefined,
            },
        });
        state.applications = res?.a?.nodes || [];
        state.totalCount = res?.a?.totalCount || 0;
        state.dataLoading = false;
    };

    const loadApplicationClients = async (appUuid) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: FindApplicationTypes,
            variables: { appUuid },
        });
        state.clients = res?.a?.nodes || [];
        state.dataLoading = false;
    };

    const loadApplicationClientVersons = async ({ appUuid, apvType }) => {
        state.dataLoading = true;
        let res = await graphqlFetchPlatform({
            query: FindApplicationTypeVersions,
            variables: { appUuid, apvType: apvType || undefined },
        });
        state.versions = res?.a?.nodes || [];
        state.dataLoading = false;
    };

    return { ...state, loadApplications, loadApplicationClients, loadApplicationClientVersons };
};

export default useApplication;
